<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Adv;
use App\Models\News;
use Illuminate\Http\Request;

class AdvController extends BaseController
{
    public $model = Adv::class;


    public function index(Request $request) {
        $input = $request->input();
        $search = ['on_status' => -1, 'start_at' => '', 'end_at' => ''];
        $list = Adv::apply($search, $input)
            ->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }


    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'position' => 'required'
        ]);
        $input = $request->input();
        $id = \request("id");
        $exist_id = Adv::where('position', \request('position'))->value('id');
        if ($id) {
            if ($exist_id && ($id != $exist_id)) {
                return $this->failed("广告位已经存在");
            }
            $model = Adv::find($id);
            $model->update($input);
        } else {
            if ($exist_id)
                return $this->failed("广告位已经存在");

            $info = Adv::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $model = Adv::find ($id);
            $model->delete();
        }
        return $this->success([]);
    }

}

